package com.qsboss.demo.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qsboss.demo.domain.Result;
import com.qsboss.demo.mapper.TbBillMapper;
import com.qsboss.demo.mapper.TbRepaymentMapper;
import com.qsboss.demo.pojo.TbBill;
import com.qsboss.demo.pojo.TbRepayment;
import com.qsboss.demo.service.TbRepaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 军哥
 * @version 1.0
 * @description: 还款处理服务层
 * @date 2023/10/25 10:35
 */

@Service
public class TbRepaymentServiceImpl implements TbRepaymentService {

    @Autowired
    TbRepaymentMapper tbRepaymentMapper;

    @Autowired
    TbBillMapper tbBillMapper;

    /***
     * @description 分页获取还款记录
     * @return com.github.pagehelper.PageInfo
     * @author 军哥
     * @date 2023/10/25 15:55
     */
    @Override
    public PageInfo getRepaymentByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        Page<TbRepayment> repaymentByPage = tbRepaymentMapper.getRepaymentByPage();

        return new PageInfo(repaymentByPage);
    }

    /***
     * @description 提交还款申请
     * @return com.qsboss.demo.domain.Result
     * @author 军哥
     * @date 2023/10/25 15:56
     */
    @Override
    public Result submitRepay(Integer billId) {

        // 检查账单
        TbBill tbBill = tbBillMapper.getBillById(billId);
        if(tbBill == null) {
            return Result.FAILED(404, "账单不存在");
        }

        if(!tbBill.getPayAck().equals(0)) {
            return Result.FAILED(500, "账单不需要处理");
        }

        // 生成还款记录
        TbRepayment tbRepayment = new TbRepayment();
        tbRepayment.setBillId(billId);
        tbRepayment.setCustomerId(tbBill.getCustomerId());
        tbRepayment.setCustomerName(tbBill.getCustomerName());
        tbRepayment.setOptId(tbBill.getOptId());
        tbRepayment.setOptName(tbBill.getOptName());
        tbRepayment.setPayAck(0);
        tbRepayment.setPayAmount(tbBill.getBillAmount());
        tbRepayment.setCreateTime(new Date());

        tbRepaymentMapper.addRepayment(tbRepayment);

        // 设置账单未销账状态
        tbBillMapper.setBillPayAck(tbBill.getBillId(), 1);

        return Result.SUCCESS();
    }

    @Override
    public Result addRepayment(TbRepayment tbRepayment) {

        tbRepaymentMapper.addRepayment(tbRepayment);

        return Result.SUCCESS();
    }
}
